package cn.nkpro.elcube.docengine.service.impl;

import cn.nkpro.elcube.docengine.model.DocHV;
import cn.nkpro.elcube.docengine.model.DocPipeline;
import cn.nkpro.elcube.docengine.service.NkDocEngineFrontService;
import cn.nkpro.elcube.docengine.service.NkPipelineService;
import cn.nkpro.elcube.utils.DateTimeUtilz;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Map;

@Slf4j
@Service
public class NkPipelineServiceImpl implements NkPipelineService {

    @Autowired
    private NkDocEngineFrontService docEngine;

    @Override
    public Map<String, Object> invoke(String docType, Map<String,String> request) {

        docType = docType.toUpperCase();

        try{


            NkPipelineService.request.set(request);

            //1、创建一个新的单据，获得其入参
            DocHV pipeline = docEngine.createForView(docType, null);
            Assert.isTrue(pipeline instanceof DocPipeline, String.format("当前单据类型[%s]不是一个有效的流水线",docType));

            // 2、通过入参所形成的businessKey获取历史流水线记录
            DocPipeline exists = (DocPipeline) docEngine.detail(docType, pipeline.getBusinessKey());

            // 3、如果有效期大于当前时间，直接返回已经存在的数据
            if(exists!=null && exists.getExpire()!=null && exists.getExpire()>= DateTimeUtilz.nowSeconds()){
                return exists.getResults();
            }

            if(exists!=null){
                pipeline = exists;
            }

            // 4、执行流水线计算
            pipeline = docEngine.calculate(pipeline, null,null);

            // 5、保存单据
            docEngine.doUpdateView(pipeline, "接口调用",null);// 这里可以记录详细一点

            // 6、返回最新结果
            return ((DocPipeline)pipeline).getResults();
        }finally {
            NkPipelineService.request.remove();
        }
    }
}
